import { bindingType } from "./types";

/**
 * 高度适配
 * @param el 指令绑定的 DOM 元素
 * @param binding 使用指令 接收的参数、修饰符等数据
 */
export const useAutoHeight = (el: HTMLDivElement, binding: bindingType) => {
    let parent = el.parentElement as HTMLDivElement // 当前元素父级

    // 获取父级计算样式
    let parentElementComputedStyle = window.getComputedStyle(parent as any)
    let paddingTop = parentElementComputedStyle.getPropertyValue("padding-top")
    let paddingBottom = parentElementComputedStyle.getPropertyValue("padding-bottom")

    // 父级所有兄弟节点
    let siblings = Array.from(parent!.parentNode!.children).filter(function (node) {
        return node !== parent;
    });

    let siblingsHeight = 0; // 父级所有兄弟节点高度
    siblings.forEach((element: Element) => {
        siblingsHeight += (element as HTMLElement).offsetHeight
    });

    // 应减去高度
    let deductHeight = (parseInt(paddingTop) + parseInt(paddingBottom)) + siblingsHeight + 100; // 100: header 和 tagsnavF 组件高度

    // 设置高度
    let setHeight = window.innerHeight - deductHeight;

    if (typeof binding.value == "number") {
        setHeight -= binding.value // 减少接收参数高度
    }

    if (el.offsetHeight >= setHeight) {
        el.style.height = setHeight + "px"
    } else {
        el.style.maxHeight = setHeight + "px"
    }
}